package com.example.demo.controller;



import com.example.demo.ResBean.constant.RedisConstant;
import com.example.demo.ResBean.constant.ResCode;
import com.example.demo.config.schedule.RedisScheduleTask;
import com.example.demo.entity.response.Response;

import com.example.demo.entity.response.ResponseToken;
import com.example.demo.entity.sqlbean.Customer;
import com.example.demo.service.CustomerService;
import com.example.demo.utils.JsonUtil;
import com.example.demo.utils.RedisUtils;
import com.example.demo.utils.TokenUtils;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

//@Api(tags = "用户入口")
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    CustomerService customerService;


    @GetMapping("unauthorized")
    public Response unauthorized(String message) {
        System.out.println("unauthorized");
        return Response.error(401, message);
    }


    @RequestMapping("/appLogin")
    public Response login(@RequestParam String data, HttpServletResponse response){
        ResponseToken res = new ResponseToken();
        Customer customer = JsonUtil.getInstance().jsonToBean(data,Customer.class);
        if (customer != null)
        {
            res.setResponse(customerService.loginCustomer(customer));
            //code=2000  则保存token
            if (res.getCode() == ResCode.Success) {
                try {
                    String username = customer.getMachineCode();
                    long currentTimeMillis = System.currentTimeMillis();
                    String token = TokenUtils.createToken(username, currentTimeMillis);
                    RedisScheduleTask.delToken(username);
                    RedisUtils.hset(RedisConstant.TOKEN_NAME + username, token, currentTimeMillis);
                    RedisUtils.expire(RedisConstant.TOKEN_NAME + username, TokenUtils.REDIS_EXPIRE_TIME);
                    response.setHeader("Authorization", token);
                    response.setHeader("Access-Control-Expose-Headers", "Authorization");
                    res.setToken(token);
                    log.info("登录成功");
                } catch (Exception e) {
                    return Response.error(1001, e.getMessage());
                }
            }

        } else {
            res.setMessage(ResCode.Param_ilegal_str);
            res.setCode(ResCode.Param_ilegal_code);
        }

        return res;
    }


    @RequestMapping("binding")
    public Response getMachineCode(@RequestParam String data){
        String id  =JsonUtil.jsonToMap(data).get("machineCode") ;
        return customerService.binding(id);

    }



}
